package cn.newshasha.hlx.controller;

import cn.newshasha.hlx.model.Post;
import cn.newshasha.hlx.model.PostsJsonRootBean;
import cn.newshasha.hlx.model.Posts;
import cn.newshasha.hlx.service.ToolsService;
import cn.newshasha.hlx.utils.HlxUtils;
import cn.newshasha.hlx.utils.HttpUtils;
import cn.newshasha.hlx.utils.RespBean;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Connection;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author bSu
 * @date 2020/11/28 - 15:49
 */
@RestController
public class ToolsController {

    private static Logger logger = Logger.getLogger(ToolsController.class);

    @Autowired
    private ToolsService toolsService;

    private static String getName(){
        return ToolsController.class.getName();
    }

    /**
     * 获取帖子内图片
     * @param postAdds  帖子链接
     * @param floor     需要获取的图片楼层
     * @return
     */
    @RequestMapping("/getImages")
    public Object getImages(@RequestBody Map<String,Object> data){
        try {
            logger.info(getName()+"/getImages()；请求开始，入参"+data.toString());
            String postAdds= (String) data.get("postAdds");
            int floor =  Integer.valueOf((String) data.get("floor"));
            if(StringUtil.isBlank(postAdds)){
                return RespBean.error("参数缺失，请输入帖子链接");
            }
            //通过传入的帖子地址获取帖子id
            long postId = HlxUtils.getPostId(postAdds);
            if(postId==0){
                return RespBean.error("查询失败，请检查后重试",null);
            }
            //通过id获取所有图片
            Map<String,Object> allImages = toolsService.getAllImages(String.valueOf(postId),postAdds,floor);
            return RespBean.ok("查询成功",allImages);
        }catch (Exception e){
            logger.error(getName()+".getImages()，Exception",e);
            return RespBean.error("查询失败",e.getMessage());
        }
    }

    /**
     *
     * @param servletResponse   响应
     * @param userId            用户id
     * @param catId             板块
     * @param month             需要导出的日期
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping("/export")
    public void test(HttpServletResponse servletResponse, String userId,String catId,String month) throws IOException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        if(StringUtil.isBlank(userId) || StringUtil.isBlank(catId) || StringUtil.isBlank(month) ){
            logger.info(getName()+"，导出失败；查询失败，参数缺失");
            return;
        }
        String postJsonUrl="http://floor.huluxia.com/post/create/list/ANDROID/2.0?start=0&count=100&user_id="+userId;
        Connection.Response response = HttpUtils.get(postJsonUrl);
        String body = response.body();
        JSONObject json=new JSONObject();
        PostsJsonRootBean jsonRootBean = json.parseObject(response.body(), PostsJsonRootBean.class);
        List<Posts> posts = jsonRootBean.getPosts();
        //List<Object> list=new ArrayList();

        //创建工作薄对象
        XSSFWorkbook workbook=new XSSFWorkbook();//这里也可以设置sheet的Name
        //创建工作表对象
        XSSFSheet sheet = workbook.createSheet();
        //创建工作表的行
        XSSFRow row = sheet.createRow(0);//设置第一行，从零开始
        row.createCell(0).setCellValue("帖子id");
        row.createCell(1).setCellValue("帖子标题");
        row.createCell(2).setCellValue("浏览量");
        row.createCell(3).setCellValue("赞");
        row.createCell(4).setCellValue("回复");
        row.createCell(5).setCellValue("葫芦");
        row.createCell(6).setCellValue("精");
        row.createCell(7).setCellValue("发帖时间");
        int i=1;
        for(Posts post : posts){
            if(String.valueOf(post.getCategory().getCategoryID()).equals(catId) && sdf.format(post.getCreateTime()).equals(month)){
                //获取是否精帖、赞的数量
                PostsJsonRootBean postDetails = HlxUtils.getPostDetails(String.valueOf(post.getPostID()));

                XSSFRow row1 = sheet.createRow(i);//设置第一行，从零开始
                row1.createCell(0).setCellValue(post.getPostID());//帖子id
                row1.createCell(1).setCellValue(post.getTitle());//标题
                row1.createCell(2).setCellValue(post.getHit());//浏览量
                row1.createCell(3).setCellValue(postDetails.getPost().getPraise());//赞
                row1.createCell(4).setCellValue(post.getCommentCount());//回复数量
                row1.createCell(5).setCellValue(post.getScore());//葫芦
                row1.createCell(6).setCellValue(postDetails.getPost().getIsGood()==1?"精":"");//精
                row1.createCell(7).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(post.getCreateTime()));//发帖时间
                i++;
                //list.add(post.getPostID());
            }
        }
        //文档输出
        /*FileOutputStream out = new FileOutputStream("D:/tmp/data/"+jsonRootBean.getPosts().get(0).getUser().getNick()  +".xls");
        workbook.write(out);*/
        //准备将Excel的输出流通过response输出到页面下载
        servletResponse.setContentType("application/vnd.ms-excel");
        //设置导出Excel的名称
        String fileName=jsonRootBean.getPosts().get(0).getUser().getNick()+month+".xlsx";
        servletResponse.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''"+ URLEncoder.encode(fileName, "UTF-8"));
        //刷新缓冲
        servletResponse.flushBuffer();
        //workbook将Excel写入到response的输出流中，供页面下载该Excel文件
        workbook.write(servletResponse.getOutputStream());
        workbook.close();
        //out.close()
        logger.info(getName()+"，执行完了，但具体导出的啥俺也不能保证");
    }

    /**
     * 通过帖子地址和楼层号获取帖子
     * @param data
     *      postAdds 帖子链接
     *      floor    楼层号
     * @return
     */
    @PostMapping("/getPostByAdds")
    public Object getPostIdByAdds(@RequestBody Map<String,Object> data) throws IOException {

        try {
            logger.info(getName()+"/getPostByAdds()；请求开始，入参"+data.toString());
            String postAdds= (String) data.get("postAdds");
            int floor =  Integer.valueOf((String) data.get("floor"));
            if(StringUtil.isBlank(postAdds)){
                return RespBean.error("参数缺失，请输入帖子链接");
            }
            long postId = HlxUtils.getPostId(postAdds);
            Object postByAdds = toolsService.getPostByAdds(postId, floor);
            return postByAdds;
        }catch (Exception e){
            return RespBean.error("查询失败，请联系管理员");
        }

    }

    /**
     * 获取板块当日帖子热度排名
     * @return
     */
    @RequestMapping("/getRanking")
    public Object getRanking(String catId) throws IOException {
        if(StringUtil.isBlank(catId)){
            return RespBean.error("数据缺失，请检查后重试");
        }
        try {
            Object ranking = toolsService.getRanking(catId);
            return RespBean.ok("查询成功",ranking);
        }catch (Exception e){
            logger.error(getName()+"/getRanking查询失败：",e);
            return RespBean.error("查询失败");
        }
    }




}
